package com.fengdi.everyday.easy;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class FindXSum {

    private class Num {
        int value; // 该数字的值
        int count; // 该数字的数量
    }

    public int[] findXSum(int[] nums, int k, int x) {
        int[] ans = new int[nums.length - k + 1];

        for(int i = 0; i < ans.length; i++) {
            int[] list = Arrays.copyOfRange(nums, i, i + k);
            ArrayList<Num> nums1 = this.countNums(list);
            int count = this.counter(nums1, x);
            ans[i] = count;
        }

        return ans;
    }

    private int counter(ArrayList<Num> nums, int x) {
        int count = 0;
        int len = Math.min(nums.size(), x);

        for(int i = 0; i < len; i++) {
            Num num = nums.get(i);
            count += num.count * num.value;
        }
        return count;
    }

    private ArrayList<Num> countNums(int[] nums) {
        // 收集元素
        ArrayList<Num> arr = new ArrayList<>();
        HashMap<Integer, Integer> map = new HashMap<>();

        for(Integer num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }

        for(Integer key : map.keySet()) {
            Num num = new Num();
            num.value = key;
            num.count = map.get(key);
            arr.add(num);
        }

        arr.sort((o1, o2) -> {
            // 先比较count（倒序）
            int countCompare = Integer.compare(o2.count, o1.count);
            if (countCompare != 0) {
                return countCompare;
            }
            // count相等时比较value（倒序）
            return Integer.compare(o2.value, o1.value);
        });

        return arr;
    }
}
